﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using ServiceStack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using XuanXiang.Infrastructure.Attr;
using XuanXiang.Infrastructure.Dto.Request;
using XuanXiang.Infrastructure.Dto.Request.Login;
using XuanXiang.Infrastructure.Dto.Request.Supplier;
using XuanXiang.Infrastructure.Dto.Response;
using XuanXiang.Infrastructure.Dto.Response.Goods;
using XuanXiang.Infrastructure.Dto.Response.Merchant;
using XuanXiang.Infrastructure.Dto.Response.Supplier;
using XuanXiang.Infrastructure.Dto.Response.System;
using XuanXiang.Infrastructure.EFCore.MySql;
using XuanXiang.Infrastructure.IOC;
using XuanXiang.Infrastructure.Redis;
using XuanXiang.Infrastructure.Tools;
using XuanXiang.Service.Interface;


namespace XuanXiang.Service.Instance
{
    [Inject_]
    public class Supplier_Service : Base_Service, I_Supplier_Service
    {
        private readonly Supplier_IOC _supplier_IOC;
        private readonly Sys_IOC _sys_IOC;
        private readonly Goods_IOC _goods_IOC;
        private readonly RedisStringService _redisStringService;
        private readonly Merchant_IOC _merchant_IOC;
        private readonly IConfiguration _configuration;
        private readonly Promote_IOC _promote_IOC;

        public Supplier_Service(Supplier_IOC supplier_IOC,
            RedisStringService redisStringService,
            Merchant_IOC merchant_IOC,
            Promote_IOC promote_IOC,
            Sys_IOC sys_IOC,
            Goods_IOC goods_IOC,
            IConfiguration configuration)
        {
            _supplier_IOC = supplier_IOC;
            _sys_IOC = sys_IOC;
            _goods_IOC = goods_IOC;
            _redisStringService = redisStringService;
            _merchant_IOC = merchant_IOC;
            _configuration = configuration;
            _promote_IOC = promote_IOC;
        }

        /// <summary>
        /// 检查供应商登录
        /// </summary>
        /// <param name="code"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        public Supplier_Dto Check_Supplier_Login(string code, string account)
        {
            var redis = _configuration["Redis:Keys:Check_Supplier_Login"];


            //获取redis中的供应商信息
            var s = _redisStringService.Get<string>(code);
            if (!string.IsNullOrEmpty(s))
            {
                return JsonConvert.DeserializeObject<Supplier_Dto>(s)!;
            }



            var jwt = _redisStringService.Get<string>(redis + account);//code
            if (code == jwt)
            {
                //返回登录的用户信息
                var supplier = _supplier_IOC._supplier_EFCore.GetAll(d => d.Saccount == account)
                     .Select(d => new Supplier_Dto()
                     {
                         id = d.Sid,
                         account = d.Saccount,
                         name = d.Sname,
                         photo = d.Sphoto,
                         logo = d.Slogo,
                         address = d.Saddress,
                         announcement = d.Sannouncement,

                     }).Single();
                //将用户存在redis中
                _redisStringService.Set(code, JsonConvert.SerializeObject(supplier), DateTime.Now.AddSeconds(88000));
                return supplier;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 获取供应商
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Supplier(Fenye_Dto dto)
        {
            var data = await _supplier_IOC._supplier_EFCore
                 .GetAll(out int total, dto.page, dto.limit, false, o => o.SorderCount, d => d.Sname.Contains(dto.key))
                 .Select(d => new Supplier_Dto()
                 {
                     id = d.Sid,
                     isActive = d.SisActive == 1 ? true : false,
                     isBan = d.SisBan == 1 ? true : false,
                     buyCount = 0,
                     canceledOrderCount = d.ScancelOrderCount,
                     cancelMoney = d.ScancelMoney,
                     completedOrderCount = d.ScompleteOrderCount,
                     name = d.Sname,
                     photo = d.Sphoto,
                     logo = d.Slogo,
                     orderCount = d.SorderCount,
                     totalMoney = d.Smoney,
                     turnoverMoney = d.ScurrMoney,
                     account = d.Saccount,
                     address = d.Saddress,
                     announcement = d.Sannouncement,
                     time = d.ScreatTime.Value.ToString("yyyy-MM-dd HH:mm:ss")
                 })
                 .ToListAsync();

            return Get_Result(0, "ok", new
            {
                data = data,
                total = total,
            });
        }

        /// <summary>
        /// 获取供应商的订单
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Supplier_Order(Fenye_Dto dto)
        {

            Expression<Func<Order, bool>> where = dto.type switch
            {
                1 => d => (d.Osid == dto.id && d.OisAccept == -1 && d.OisComplete == 0 && d.OisCancel == 0),//未接单
                2 => d => (d.Osid == dto.id && d.OisAccept == 1 && d.OisCancel == 0 && d.OisComplete == 0),//进行中
                3 => d => (d.Osid == dto.id && d.OisComplete == 1 && d.OisReceive == 1 && d.OisSend == 1),//已完成
                4 => d => (d.Osid == dto.id && d.OisCancel == 1 && d.OcancelType == 2),//已取消 2代表供应商取消
            };


            var data = await _merchant_IOC._orders_EFCore
                .GetAll(out int total, dto.page, dto.limit, false, o => o.OcreateTime, where)
                .Select(d => new SupplierOrders_Dto()
                {
                    id = d.Oid,
                    isAccept = d.OisAccept,
                    isCancel = d.OisCancel,
                    isComplete = d.OisComplete,
                    isReceive = d.OisReceive,
                    isSend = d.OisSend,
                    money = d.Omoney,
                    mid = d.Omid,
                    cancelTime = d.OcancelTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), //取消时间
                    completeTime = d.OcompleteTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), //完成时间
                    sendTime = d.OsendTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), //发货时间
                    time = d.OcreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"), //创建时间/下单时间
                    receiveTime = d.OreceiveTime.Value.ToString("yyyy-MM-dd HH:mm:ss") //收货时间

                }).ToListAsync();

            //获取所有商户
            var merchant = _merchant_IOC._merchant_EFCore.GetAll().ToList();
            //获取所有商品详情
            var details = _merchant_IOC._order_Details_EFCore.GetAll()
                .Select(e => new Supplier_OrderDetails_Dto()
                {
                    id = e.OdId,
                    oid = e.OdOid,
                    gid = e.OdGid,
                    number = e.OdNumber,
                    name = e.OdName,
                    isCancel = e.OdIsCancel,
                    isComplete = e.OdIsComplete,
                    isDirectly = e.OdIsDirectly,
                    isPromote = e.OdIsPromote,
                    isReceive = e.OdIsReceive,
                    isSend = e.OdIsSend,
                    photo = e.OdPhoto,
                    price = e.OdIsPromote == 1 ? e.OdPromotePrice : e.OdPrice,
                    specs = e.OdSpecs,
                    d_brithday = e.OdBirthday,
                    d_cancelTime = e.OdCancelTime,
                    d_sendTime = e.OdSendTime,
                    d_expiryDate = e.OdExpiryday


                }).ToList();
            details.ForEach(e =>
            {
                e.brithday = e.d_brithday?.ToString("yyyy-MM-dd");
                e.expiryDate = e.d_brithday?.AddDays(e.d_expiryDate ?? 0).ToString("yyyy-MM-dd");
                e.cancelTime = e.d_cancelTime?.ToString("yyyy-MM-dd HH:mm:ss");
                e.sendTime = e.d_sendTime?.ToString("yyyy-MM-dd HH:mm:ss");
            });

            data.ForEach(d =>
            {
                d.merchant = merchant.Where(c => c.MId == d.mid).Select(c => c.MName).SingleOrDefault();
                d.goods = details.Where(c => c.oid == d.id).ToList();
            });

            return Get_Result(0, "ok", new
            {
                total = total,
                data = data
            });
        }

        /// <summary>
        /// 供应商的禁用/启用
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> IsBan_Supplier(IsBan_Dto dto)
        {
            var data = await _supplier_IOC._supplier_EFCore.GetAll(d => d.Sid == dto.id).SingleOrDefaultAsync();
            data.SisBan = dto.isBan;
            _supplier_IOC._supplier_EFCore.Update(data);
            var result = await _supplier_IOC._supplier_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }


        /// <summary>
        /// 供应商登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Supplier_Logins(Login_dto dto)
        {
            var iq = _supplier_IOC._supplier_EFCore.GetAll(d => d.Saccount == dto.account);
            if (!await iq.AnyAsync())
            {
                //不相等,登录失败
                return Get_Result(-1, "账号或者密码错误!");
            }
            var supplier = await iq.SingleAsync();
            var pwd = EncryptUtil.LoginMd5(dto.password, supplier.Ssalt);
            if (supplier.Spassword != pwd)
            {
                return Get_Result(-1, "账号或者密码错误!");
            }

            if (supplier.SisBan == 1)
            {
                return Get_Result(-1, "账号已禁用!");
            }

            //登录成功
            //添加登录日志
            SupplierLoginLog supplierLoginLog = new SupplierLoginLog()
            {
                SLlid = Config.GUID(),
                SLlcode = dto.code,
                SLlip = Config.GetIp(),
                SLlsid = supplier.Sid,
                SCreateTime = DateTime.Now
            };
            _supplier_IOC._supplier_LoginLogs_EFCore.Add(supplierLoginLog);

            if (supplier.SisActive == 0)
            {
                supplier.SisActive = 1;
                _supplier_IOC._supplier_EFCore.Update(supplier);
            }

            //事务
            var result = _supplier_IOC._supplier_LoginLogs_EFCore.Transactions(_supplier_IOC._supplier_EFCore);

            //添加到redis
            //保存code到redis
            var jwt = _configuration["Redis:Keys:Check_Supplier_Login"];
            _redisStringService.Set<String>(jwt + supplier.Saccount, dto.code!, DateTime.Now.AddSeconds(86400));


            return Get_Result(result ? 0 : -1);
        }

        /// <summary>
        /// 获取供应商所有的类别和商品
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Supplier_AllType(Fenye_Dto dto)
        {
            var iq = _sys_IOC._sys_Dictionary_EFCore
                .GetAll(d => d.Dsid == dto.id && d.DisBan==0);

            var tid = iq.Select(d => d.Did).ToList();
            var allDetails = _goods_IOC._goods_EFCore
              .GetAll(e => tid.Contains(e.Gtype!) && e.GisPromote == 0 && e.GSid==dto.id)
              .ToList();

            var type = await iq.ToListAsync();

            //当前供应商名字
            var supplier = _supplier_IOC._supplier_EFCore.GetAll(d => d.Sid == dto.id).Select(d => d.Sname).SingleOrDefault();

            var data = type.Select(d => new SupplierAllType_Dto
            {
                id = d.Did,
                count = allDetails.Where(e => e.Gtype == d.Did).ToList().Count(),
                explain = d.Dexplain,
                name = d.Dname,
                icon = d.Dicon,
                goods = allDetails
                .Where(e => e.Gtype == d.Did )
                .Select(e => new Supplier_Type_Goods()
                {
                    id = e.Gid,
                    brithday = e.Gbirthday!.Value.ToString("yyyy-MM-dd"),
                    expiryday = e.Gexpiryday,
                    sales = e.Gsales,
                    explain = e.Gexplain,
                    inventory = e.Ginventory,
                    isBan = e.GisBan,
                    isPromote = e.GisPromote,
                    isShelve = e.GisShelve,
                    name = e.Gname,
                    photo = e.Gcover,
                    price = e.Gprice,
                    promotePrice = e.GpromotePrice,
                    specs = e.Gspecs,
                    type = e.Gtype,
                    supplier = supplier
                }).ToList()

            }).ToList();

            var details = _goods_IOC._goods_EFCore
              .GetAll(e => e.GisPromote == 1 && e.GSid == dto.id)
              .ToList();

            data.Add(new SupplierAllType_Dto
            {
                id = "-1",
                name = "折扣商品",
                explain = "",
                count = details.Count(),
                goods = details.Select(e => new Supplier_Type_Goods
                {
                    id = e.Gid,
                    brithday = e.Gbirthday!.Value.ToString("yyyy-MM-dd"),
                    expiryday = e.Gexpiryday,
                    sales = e.Gsales,
                    explain = e.Gexplain,
                    inventory = e.Ginventory,
                    isBan = e.GisBan,
                    isPromote = e.GisPromote,
                    isShelve = e.GisShelve,
                    name = e.Gname,
                    photo = e.Gcover,
                    price = e.Gprice,
                    promotePrice = e.GpromotePrice,
                    specs = e.Gspecs,
                    type = e.Gtype
                }).ToList()

            });

            data = data.OrderByDescending(item => item.id == "-1").ToList();


            return Get_Result(0, "ok", data);

        }

        /// <summary>
        /// 供应商-确认/拒绝接单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Supplier_AcceptOrder(IsBan_Dto dto)
        {
            var data = _supplier_IOC._orders_EFCore.GetAll(d => d.Oid == dto.id).SingleOrDefault();
            if (dto.isAccept == 1)
            {
                //接单
                data!.OisAccept = dto.isAccept;
                data!.OacceptTime = DateTime.Now;
            }
            else
            {
                //拒绝
                data!.OisAccept = dto.isAccept;
                data!.OacceptTime = null;
            }

            _supplier_IOC._orders_EFCore.Update(data);
            var result = await _supplier_IOC._orders_EFCore.SaveChangesAsync();
            return Get_Result(result);

        }

        /// <summary>
        /// 供应商订单-发货/取消发货
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Supplier_SendOrder(IsBan_Dto dto)
        {
            var data = _supplier_IOC._orders_EFCore.GetAll(d => d.Oid == dto.id).SingleOrDefault();
            if (dto.isSend == 1)
            {
                //发货
                data!.OisSend = dto.isSend;
                data!.OsendTime = DateTime.Now;
            }
            else
            {
                //未发货
                data!.OisSend = dto.isSend;
                data!.OsendTime = null;
            }

            _supplier_IOC._orders_EFCore.Update(data);


            var orderDetails = _supplier_IOC._order_Details_EFCore.GetAll(d => d.OdOid == dto.id).ToList();
            orderDetails.ForEach(d =>
            {
                if (dto.isSend == 1)
                {
                    //发货
                    d.OdIsSend = dto.isSend;
                    d.OdSendTime = DateTime.Now;
                }
                else
                {
                    //未发货
                    d.OdIsSend = dto.isSend;
                    d.OdSendTime = null;
                }
            });
            _supplier_IOC._order_Details_EFCore.UpdateRange(orderDetails);

            var result = _supplier_IOC._orders_EFCore.Transactions(_supplier_IOC._order_Details_EFCore);
            return Get_Result(result ? 0 : -1);
        }

        /// <summary>
        /// 供应商-取消订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Supplier_CancelOrder(IsBan_Dto dto)
        {
            //订单
            var data = _supplier_IOC._orders_EFCore.GetAll(d => d.Oid == dto.id).SingleOrDefault();
            data!.OisCancel = dto.isCancel;
            data!.OcancelTime = DateTime.Now;
            data!.OcancelType = 2;
            data!.OisSend = 0;
            data!.OsendTime = null;
            _supplier_IOC._orders_EFCore.Update(data);

            //订单详情
            var orderDetails = _supplier_IOC._order_Details_EFCore.GetAll(d => d.OdOid == dto.id).ToList();
            orderDetails.ForEach(d =>
            {
                d.OdIsCancel = dto.isCancel;
                d.OdCancelTime = DateTime.Now;
                d.OdIsSend = 0;
                d.OdSendTime = null;
            });
            _supplier_IOC._order_Details_EFCore.UpdateRange(orderDetails);

            //修改供应商的取消订单
            var supplier = await _supplier_IOC._supplier_EFCore.GetAll(d => d.Sid == dto.sid).SingleOrDefaultAsync();
            supplier!.ScancelOrderCount += 1;
            _supplier_IOC._supplier_EFCore.Update(supplier);

            var result = _supplier_IOC._orders_EFCore.Transactions(_supplier_IOC._order_Details_EFCore, _supplier_IOC._supplier_EFCore);
            return Get_Result(result ? 0 : -1);
        }

        /// <summary>
        /// 供应商-上下架商品
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Supplier_isShelveGoods(IsBan_Dto dto)
        {
            var data = _goods_IOC._goods_EFCore.GetAll(d => d.Gid == dto.id).SingleOrDefault();
            data.GisShelve = dto.isShelve;
            _goods_IOC._goods_EFCore.Update(data);
            var result = await _goods_IOC._goods_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 供应商-新增商品
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Supplier_AddGoods(Supplier_AddGoods_Dto dto)
        {
            Good goods = new Good()
            {
                Gid = Config.GUID(),
                Gbirthday = DateTime.Parse(dto.birthday!),
                Gcover = dto.photo,
                GcreateTime = DateTime.Now,
                Gexpiryday = dto.expiryday,
                Gexplain = dto.explain,
                Ginventory = 0,
                Gspecs = dto.specs,
                GisBan = 0,
                GisPromote = 0,
                GisShelve = 0,
                Gloss = 0,
                Gname = dto.name,
                Gprice = dto.price,
                GpromoteBegin = null,
                GpromoteEnd = null,
                GpromotePrice = 0,
                Gsales = 0,
                GSid = dto.sid,
                Gtype = dto.type

            };

            _goods_IOC._goods_EFCore.Add(goods);
            var result = await _goods_IOC._goods_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 供应商-设置活动商品
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Supplier_SetPromoteGoods(Supplier_SetPromoteGoods_Dto dto)
        {
            Promote promote = new Promote()
            {
                Pid = Config.GUID(),
                PbeginTime = DateTime.Parse(dto.startTime!),
                PcreateTime = DateTime.Now,
                PendTime = DateTime.Parse(dto.endTime!),
                Pgid = dto.gid,
                Pgname = dto.goodsName,
                PinitPrice = dto.price,
                PpromotePrice = dto.promotePrice,
                Psid = dto.sid,
            };
            _promote_IOC._promote_EFCore.Add(promote);
            _promote_IOC._promote_EFCore.SaveChanges();

            //修改商品表中的商品数据
            //找到对应的商品
            var data = _goods_IOC._goods_EFCore.GetAll(d => d.Gid == dto.gid).SingleOrDefault();
            //修改商品的活动状态
            data!.GisPromote = 1;
            data!.GpromoteBegin = DateTime.Parse(dto.startTime!);
            data!.GpromoteEnd = DateTime.Parse(dto.endTime!);
            data!.GpromotePrice = dto.promotePrice;

            _goods_IOC._goods_EFCore.Update(data);
            var result = await _goods_IOC._goods_EFCore.SaveChangesAsync();
            return Get_Result(result);

        }


        /// <summary>
        /// 供应商-取消活动商品折扣
        /// </summary>
        /// <param name="gid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Supplier_CancelPromoteGoods(string? gid)
        {
            //删除该商品的活动
            var data = _promote_IOC._promote_EFCore.GetAll(false,o=>o.PcreateTime,d => d.Pgid == gid).First();
            _promote_IOC._promote_EFCore.Delete(data);
            _promote_IOC._promote_EFCore.SaveChanges();

            //修改商品的活动状态
            var goods = _goods_IOC._goods_EFCore.GetAll(d => d.Gid == gid).Single();
            goods.GisPromote = 0;
            goods.GpromoteBegin = null;
            goods.GpromoteEnd = null;
            goods.GpromotePrice = 0;
            _goods_IOC._goods_EFCore.Update(goods);
            var result = await _goods_IOC._goods_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 供应商-新增商品类别
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Supplier_AddType(Supplier_AddType_Dto dto)
        {
            var pid = _sys_IOC._sys_Dictionary_EFCore.GetAll(d => d.Dname == "商品类型").Select(d => d.Did).SingleOrDefault();

            SysDictionary type = new SysDictionary()
            {
                Did = Config.GUID(),
                DcreateTime = DateTime.Now,
                Dexplain = dto.explain,
                Dicon = dto.icon,
                DisBan = 0,
                DisType = 0,
                Dname = dto.name,
                Dno = 0,
                Dsid = dto.sid,
                DparentId = pid,
                Dvalue = null
            };

            _sys_IOC._sys_Dictionary_EFCore.Add(type);
            var result = await _sys_IOC._sys_Dictionary_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 供应商-编辑商品类型
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Supplier_UpdateGoodsType(Supplier_Update_Type_Dto dto)
        {
            var type = _sys_IOC._sys_Dictionary_EFCore.GetAll(d => d.Did == dto.id).Single();
            type.Dname = dto.name;
            type.Dexplain = dto.explain;
            _sys_IOC._sys_Dictionary_EFCore.Update(type);
            var result = await _sys_IOC._sys_Dictionary_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 供应商-删除商品类型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Supplier_DeleteGoodsType(string? id)
        {
            //找到删除的类型
            var data = _sys_IOC._sys_Dictionary_EFCore.GetAll(d => d.Did == id).SingleOrDefault();
            _sys_IOC._sys_Dictionary_EFCore.Delete(data);
            var result = await _sys_IOC._sys_Dictionary_EFCore.SaveChangesAsync();
            return Get_Result(result);

        }

        /// <summary>
        /// 获取单个供应商
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Single_Supplier(string? id)
        {
            var data = await _supplier_IOC._supplier_EFCore.GetAll(d => d.Sid == id)
                .Select(d => new Supplier_Single_Dto()
                {
                    id = d.Sid,
                    name = d.Sname,
                    enterpriseName = d.SenterpriseName,
                    account = d.Saccount,
                    cancelMoney = d.ScancelMoney,
                    isActive = d.SisActive,
                    cancelOrderCount = d.ScancelOrderCount,
                    completeOrderCount = d.ScompleteOrderCount,
                    isBan = d.SisBan,
                    logo = d.Slogo,
                    money = d.ScurrMoney,
                    orderCount = d.SorderCount,
                    photo = d.Sphoto,
                    time = d.ScreatTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"),


                }).SingleOrDefaultAsync();

            //获取所有的商品
            var goods = _goods_IOC._goods_EFCore.GetAll().ToList();
            //获取所有订单
            var orders = _supplier_IOC._orders_EFCore.GetAll().ToList();
            data.goodsCount = goods.Where(c => c.GSid == data.id).Count();
            data.goodsSalesCount = goods.Where(c => c.GSid == data.id).Sum(c => c.Gsales);
            data.sendOrderCount = orders.Where(c => c.Osid == data.id && c.OisSend == 1).Count();
            data.receiveOrderCount = orders.Where(c => c.Osid == data.id && c.OisReceive == 1).Count();

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 获取供应商数据/商品
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Supplier_Goods(Fenye_Dto dto)
        {
            var data = await _goods_IOC._goods_EFCore
                .GetAll(out int total, dto.page, dto.limit, false, o => o.GcreateTime, d => d.GSid == dto.id)
                .Select(d => new Goods_Dto()
                {
                    id = d.Gid,
                    name = d.Gname,
                    photo = d.Gcover,
                    price = d.Gprice,
                    tId = d.Gtype,
                    s_id = d.GSid,
                    inventory = d.Ginventory,
                    sales = d.Gsales,
                    isBan = d.GisBan == 1 ? true : false,
                    isShelve = d.GisShelve == 1 ? true : false,
                    time = d.GcreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss")

                }).ToListAsync();

            //获取所有商品类型
            var type = _sys_IOC._sys_Dictionary_EFCore.GetAll().ToList();
            //获取所有的供应商
            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();

            data.ForEach(d =>
            {
                d.typeName = type.Where(c => c.Did == d.tId).Select(c => c.Dname).SingleOrDefault();
                d.supplierName = supplier.Where(c => c.Sid == d.s_id).Select(c => c.Sname).SingleOrDefault();
            });

            return Get_Result(0, "ok", new
            {
                data = data,
                total = total
            });
        }

        /// <summary>
        /// 供应商畅销商品/订单
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Supplier_Orders(Fenye_Dto dto)
        {
            var data = await _supplier_IOC._orders_EFCore
                .GetAll(out int total, dto.page, dto.limit, false, o => o.OcreateTime, d => d.Osid == dto.id)
                .Select(d => new Supplier_Top_Goods_Dto()
                {
                    id = d.Oid,
                    goodsName = d.OgoodsNames,
                    money = d.Omoney,
                    m_id = d.Omid,
                    s_id = d.Osid,
                    number = d.Ototal,
                    time = d.OcreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                }).ToListAsync();

            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();
            var merchant = _merchant_IOC._merchant_EFCore.GetAll().ToList();
            data.ForEach(d =>
            {
                d.merchant = merchant.Where(c => c.MId == d.m_id).Select(c => c.MName).SingleOrDefault();
                d.supplier = supplier.Where(c => c.Sid == d.s_id).Select(c => c.Sname).SingleOrDefault();
            });

            return Get_Result(0, "ok", new
            {
                data = data,
                total = total
            });
        }

        /// <summary>
        /// 供应商-获取我的订单数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Supplier_GetOrderData(string? id)
        {
            //获取供应商的所有订单
            var order = await _supplier_IOC._orders_EFCore.GetAll(d => d.Osid == id).ToListAsync();

            Supplier_OrderData_Dto data = new Supplier_OrderData_Dto()
            {
                orderCount = order.Count,//总订单数
                completeCount = order.Where(c => c.OisComplete == 1).Count(),//完成量
                completeMoney = order.Where(c => c.OisComplete == 1).Sum(d => d.Omoney),//完成额
                saleMoney = order.Sum(d => d.Omoney) //销售额
            };

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 获取销售数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto>  Supplier_GetSalesData(string? id)
        {
            Supplier_Total_Data_Dto data = new Supplier_Total_Data_Dto();
            DateTime today = DateTime.Today;
            DateTime startDate = today.AddDays(-6); // 从6天前开始

            List<string> lastSevenDays = new List<string>();
            List<double?> dailySalesAmounts = new List<double?>();
            List<double?> dailyTransactionAmounts = new List<double?>();
            List<int?> orderCount = new List<int?>();
            List<int?> completeCount = new List<int?>();

            var allOrders = await _supplier_IOC._orders_EFCore.GetAll(d => d.Osid == id).ToListAsync();

            // 循环6天前到今天（共7天）
            for (int i = 0; i <= 6; i++)
            {
                DateTime targetDate = startDate.AddDays(i);
                string formattedDate = targetDate.ToString("MM-dd");
                lastSevenDays.Add(formattedDate);

                // 筛选当天订单
                var dailyOrders = allOrders.Where(c =>
                    c.OcreateTime >= targetDate.Date &&
                    c.OcreateTime < targetDate.AddDays(1).Date
                ).ToList();


                // 计算当天数据，并保留两位小数
                double? dailySales = dailyOrders.Any() ?
                    Math.Round(dailyOrders.Sum(c => c.Omoney) ?? 0, 2) : 0;
                double? dailyTransaction = dailyOrders.Where(c => c.OisComplete == 1).Any() ?
                    Math.Round(dailyOrders.Where(c => c.OisComplete == 1).Sum(c => c.Omoney) ?? 0, 2) : 0;
                int? order_count = dailyOrders.Count();
                int? complete_count = dailyOrders.Where(c => c.OisComplete == 1).Count();

                dailySalesAmounts.Add(dailySales);
                dailyTransactionAmounts.Add(dailyTransaction);
                orderCount.Add(order_count);
                completeCount.Add(complete_count);
            }

            lastSevenDays.Reverse();
            dailySalesAmounts.Reverse();
            dailyTransactionAmounts.Reverse();
            orderCount.Reverse();
            completeCount.Reverse();

            data.xAxisData = lastSevenDays;
            data.saleMoney = dailySalesAmounts;
            data.completeMoney = dailyTransactionAmounts;
            data.orderCount = orderCount;
            data.completeCount = completeCount;

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 供应商-商品补货
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Supplier_AddInventory(Supplier_AddInventory_Dto dto)
        {
            var data = _goods_IOC._goods_EFCore.GetAll(d => d.Gid == dto.id).SingleOrDefault();
            data.Ginventory += dto.number;
            _goods_IOC._goods_EFCore.Update(data);
            var result = await _goods_IOC._goods_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 获取指定日期的订单数据
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Supplier_GetDateOrderData(DateTime? startTime, DateTime? endTime)
        {
            Supplier_Total_Data_Dto data = new Supplier_Total_Data_Dto();
            List<string> dateRange = new List<string>();
            List<int?> orderCount = new List<int?>();
            List<int?> completeCount = new List<int?>();
            List<double?> dailySalesAmounts = new List<double?>();//销售额
            List<double?> dailyTransactionAmounts = new List<double?>();//成交额

            var allOrders = await _supplier_IOC._orders_EFCore.GetAll().ToListAsync();


            DateTime start = startTime.Value;
            DateTime end = endTime.Value;

            // 获取时间范围内的所有日期
            TimeSpan span = end - start;
            for (int i = 0; i <= span.Days; i++)
            {
                DateTime currentDate = start.AddDays(i);
                string formattedDate = currentDate.ToString("MM-dd");
                dateRange.Add(formattedDate);

                // 筛选当天订单
                var dailyOrders = allOrders.Where(c =>
                    c.OcreateTime >= currentDate.Date &&
                    c.OcreateTime < currentDate.AddDays(1).Date
                ).ToList();
                double? dailySales = dailyOrders.Any() ?
                   Math.Round(dailyOrders.Sum(c => c.Omoney) ?? 0, 2) : 0;
                double? dailyTransaction = dailyOrders.Where(c => c.OisComplete == 1).Any() ?
                    Math.Round(dailyOrders.Where(c => c.OisComplete == 1).Sum(c => c.Omoney) ?? 0, 2) : 0;
              
                int? order_count = dailyOrders.Count();
                int? complete_count = dailyOrders.Where(c => c.OisComplete == 1).Count();
                dailySalesAmounts.Add(dailySales);
                dailyTransactionAmounts.Add(dailyTransaction);
                orderCount.Add(order_count);
                completeCount.Add(complete_count);
            }


            data.xAxisData = dateRange;
            data.saleMoney = dailySalesAmounts;
            data.completeMoney = dailyTransactionAmounts;
            data.orderCount = orderCount;
            data.completeCount = completeCount;

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 删除供应商
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Delete_Supplier(string? id)
        {
            var supplier =await _supplier_IOC._supplier_EFCore.GetAll(d=>d.Sid==id).SingleAsync();
            _supplier_IOC._supplier_EFCore.Delete(supplier);
            var result = await _supplier_IOC._supplier_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 新增供应商
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Add_Supplier(Supplier_Add_Dto dto)
        {
            Supplier supplier = new Supplier() {
                Sid = Config.GUID(),
                SisActive = 0,
                Saccount = dto.phone,
                Saddress = dto.address,
                Sannouncement = dto.announcement,
                ScancelMoney = 0,
                Slogo=dto.logo,
                Sname=dto.name,
                Sphoto=dto.photo,
                ScancelOrderCount=0,
                ScompleteOrderCount=0,
                ScreatTime=DateTime.Now,
                ScurrMoney=0,
                SenterpriseName=null,
                SisBan=0,
                Smoney=0,
                SopenId=null,
                SorderCount=0,
                Spassword="123456",
                Squalification=null,
                Ssalt=null,
                Stype=null
            };

            _supplier_IOC._supplier_EFCore.Add(supplier);
           await _supplier_IOC._supplier_EFCore.SaveChangesAsync();

            //初始化密码
           
                var salt = Config.GUID2();
                supplier.Ssalt = salt;
                supplier.Spassword = EncryptUtil.LoginMd5("123456", salt);

         
            var result =await _supplier_IOC._supplier_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }
    }
}
